// components/signature/signature.js
// canvas 全局配置
import {config} from "../../utils/config";


Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
      observer(val){
        if(val){
          setTimeout(() =>{
            this.init();
          },100)
        }
      }
    },
    mark: {
      type: Array,
      value: []
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    canvasStyle: {}
  },

  /**
   * 组件的方法列表
   */
  methods: {
    init(){
      let that = this;
      this.data.hasDraw = false;
      wx.createSelectorQuery().in(this)
        .select("#canvas")
        .fields({
          node:true,
          size:true
        }).exec((res)=>{
        let canvas = res[0].node;
        let ctx = canvas.getContext("2d");
        let dpr = wx.getSystemInfoSync().pixelRatio;
        // canvas.width = res[0].width * dpr;
        // canvas.height = res[0].height * dpr;
        canvas.width = res[0].width;
        canvas.height = res[0].height;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0,0,canvas.width ,canvas.height)
        ctx.lineWidth = 5;
        // 利用阴影，消除锯齿
        ctx.shadowBlur = 1;
        ctx.shadowColor = '#000';
        // ctx.scale(dpr, dpr)
        that.setData({
          canvas,
          ctx
        })
      })
    },

    //触摸开始
    start (e) {
      this.data.hasDraw = true;
      this.data.ctx.beginPath()
      this.data.ctx.moveTo(e.touches[0].x,e.touches[0].y)
    },
    //触摸移动
    move (e) {
      this.data.ctx.lineTo(e.touches[0].x, e.touches[0].y)
      this.data.ctx.stroke()//将上下文绘制到canvas中
      console.log('触摸移动');
    },
    //触摸结束
    end (e) {
      this.data.ctx.closePath()
    },
    //清除画布内容
    clear(){
      this.data.hasDraw = false;
      this.data.ctx.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height)
      this.setData({
        canvanImg:""
      })
    },
    //点击保存生成图片
    save(){
      let This = this;
      if (!This.data.hasDraw ) {
        wx.$toast('请签名确认');
        return
      }
      let url = this.data.canvas.toDataURL("image/jpeg");
      this.getWatermarkData().then(opts => {

/*
        let {address,nowTime} = res,
          car = wx.getStorageSync('driver_car_name');
        let opts = [{
          content: address,
          font: '14px serif',
          position: {
            bottom: 20,
            left: 15
          }
        },
          {
            content: car,
            font: '24px serif',
            position: {
              bottom: 50,
              left: 15
            }
          },
          {
            content: nowTime,
            font: '25px serif',
            position: {
              bottom: 80,
              left: 15
            }
          },];*/
        This.addWatermark(url,opts).then(res =>{
          this.triggerEvent('sign', res)
        })
        this.setData({
          canvanImg: url
        })
      });
    },
    cancel(){
      this.triggerEvent('cancel')
    },


    /**
     * 签名添加水印
     * @param src 签名图片地址base64
     * @param opts 水印参数
     * @return {Promise<any>} 返回已添加水印的签名图片地址base64
     */
    addWatermark(src,opts) {
      return new Promise((resolve,reject) => {
        let that = this
        wx.createSelectorQuery().in(this)
          .select('#mycanvas')
          .fields({ node: true, size: true })
          .exec((res) => {
            const canvas = res[0].node
            const context = canvas.getContext('2d');
            let img = canvas.createImage(); // 注意是使用canvas实例 不是context
            img.src = src; // 带编码的头信息的base64字符串    
            img.onload = () => {
              let rotate = -90;  //旋转角度
              const {width, height} = img;
              canvas.width = height;
              canvas.height = width;
              that.setData({
                canvasStyle: `width: ${height}rpx;height: ${width}rpx;`
              })
              context.clearRect(0, 0, canvas.width, canvas.height)
              context.translate(canvas.width / 2, canvas.height / 2)
              context.rotate(rotate * Math.PI / 180)
              context.translate(-canvas.width / 2, -canvas.height / 2)
              context.drawImage(img,canvas.width / 2 - width / 2, canvas.height / 2 - height / 2,width,height)
              context.translate(canvas.width / 2, canvas.height / 2)
              context.rotate(-rotate * Math.PI / 180)
              context.translate(-canvas.width / 2, -canvas.height / 2)
              context.restore();


              //添加水印
              this.fillText(context, opts,height ,width );

              /*延迟画完之后再转成文件*/
              setTimeout(() =>{
                // canvas转二进制对象转文件对象，返回
                wx.canvasToTempFilePath({
                  canvas: canvas,
                  // destWidth: targetWidth, //目标宽度
                  // destHeight: targetHeight, //目标高度
                  fileType: 'jpg',
                  success: (res) => {
                    // file.path = res.tempFilePath;
                    resolve(res.tempFilePath)
                  },
                  fail(err){}
                },this)
              },600)
              /*let base64 = canvas.toDataURL();

              resolve(base64);*/
            }
          })
      })
    },

    /**
     * 画布画文字
     * @param ctx canvas上下文
     * @param opts {Array} 定义文字参数数组
     * opts: {
     *   textAlign: // 水印文字的对齐方式
     *   font: "16px Microsoft Yahei", // 水印文字的字体
     *   textBaseline: "middle", // 水印文字的基线
     *   fillStyle: "rgba(184, 184, 184, 0.6)", // 水印文字的填充样式
     *   content: '名称', // 水印文字的内容
     *   rotate: -30, // 水印文字的旋转角度
     *   zIndex: 10000, // 水印的 z-index 值
     *   position: {
     *     top: 0,
     *     left: 0,
     *     right: 0,
     *     bottom: 0
     *   }
     *   top: '',   //水印位置top
     *   left: '',  //水印位置right
     * }
     * @param width 画布宽度
     * @param height 画布高度
     */
    fillText (ctx,opts, width ,height){
      opts.forEach(item => {
        let {content,textAlign,font ,textBaseline ,fillStyle ,rotate ,zIndex,position } = item;
        textAlign && (ctx.textAlign = textAlign);
        textBaseline && (ctx.textBaseline = textBaseline);
        ctx.font = font || '16px serif';
        ctx.fillStyle = fillStyle || '#ffffff';
        rotate && ctx.rotate((Math.PI / 180) * rotate);
        let x = 0,y = 0,
          metrics = ctx.measureText(content),
          textWidth = metrics.width,
          textHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;

        if (position){
          let {left, top, bottom, right} = position;
          //计算文字位置
          x = right ? width - right - textWidth : 0;
          x = left ? left : x;  //left 优先于 right
          x = x > width ? width - textWidth : x;  //超出画布宽度
          x = x < 0 ? 0 : x;  //小于画布

          y = bottom ? height - bottom : 0;
          y = top ? top + textHeight : y;  //top 优先于 bottom
          y = y > height ? height : y < 0 ? 0 : y;  //超出画布宽度
        }
        //空心描边
        ctx.lineWidth = 3;
        ctx.strokeStyle = '#000';
        ctx.strokeText(content, x, y);
        ctx.fillText(content,x,y);// 绘制文字，实心填充

      })
    },

    /**
     * 获取水印信息
     * */
    getWatermarkData(){
      return new Promise(async resolve => {
        let {mark} = this.data,
          opts = [];
        for (let i = 0; i< mark.length;i++){
          let item = {...mark[i]};
          //定位
          if (item.content === '$location$'){
            wx.showLoading({mask: true});
            await this.wxLocation().then(res => {
              wx.hideLoading();
              let {address,location,formatted_addresses} = res.result;
              address = formatted_addresses && formatted_addresses.recommend || address;
              item.content = address;
            },() =>{
              wx.hideLoading();
              wx.showModal({
                title: '定位服务未打开',
                content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
                confirmText: '确定',
                showCancel: false,
                success: (res) => {
                  if(res.confirm) {
                    wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
                  }
                },

              });
            })
          }
          if (item.content === '$time$'){
            item.content = wx.$util.formatDate(new Date(),'yyyy-MM-dd HH:mm');
          }
          opts.push(item);
        }
        resolve(opts);
      })
    },

    //  获取当前位置
    wxLocation(){
      return new Promise((resolve,reject) => {
        wx.$getLocation().then(res =>{
          this.mapGeocoder(res).then(result => {
            resolve(result);
          })
        },reject)
      })
    },

    //腾讯地图api逆地址转换
    mapGeocoder(latlng){
      let url = 'map/tencent/ws/geocoder/location';
      let{latitude, longitude} = latlng;
      return new Promise(resolve => {
        wx.$post(2,url,{
          "key": config.mapKey,
          "location": `${latitude},${longitude}`,
          "get_poi": "",
          "poi_options": "",
          "output": "",
          "callback": ""
        },false,true).then(res =>{
          resolve(res)
        })
      })
    },
  },



  // 生命周期
  lifetimes: {
    created() {},
    ready() {},
    attached(){},
    moved() {},
    detached() {},
    error() {},
  },
})
